{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# -*-coding:utf-8-*-\n",
    "\n",
    "import zipfile\n",
    "import os\n",
    "\n",
    "epub = zipfile.ZipFile('H:\\\\file.epub', 'w')\n",
    "epub.writestr('mimetype', 'application/epub+zip')\n",
    "asd = os.listdir('H:\\\\ttt')\n",
    "\n",
    "html_files = ['H:\\\\ttt\\\\'+ i for i in asd]\n",
    "\n",
    "epub.writestr('META-INF/container.xml', '''<container version=\"1.0\"\n",
    "\t\t   xmlns=\"urn:oasis:names:tc:opendocument:xmlns:container\">\n",
    "\t<tootfiles>\n",
    "\t  <rootfile full-path=\"OEBPS/Content.opf\" media-type=\"application/oebps-package+xml\"/>\n",
    "\t</rootfiles>\n",
    "</container>''')\n",
    "index_tpl = '''<package version=\"2.0\n",
    "  xmlns=\"http://www.idpf.org/2007/opf\">\n",
    "  <metadata/>\n",
    "  <manifest>\n",
    "    %(manifest)s\n",
    "  </manifest>\n",
    "  <spine toc=\"ncx\">\n",
    "    %(spine)s\n",
    "  </spine>\n",
    "</package>'''\n",
    "manifest = \"\"\n",
    "spine = \"\"\n",
    "\n",
    "for i, html in enumerate(html_files):\n",
    "    basename = os.path.basename(html)\n",
    "    manifest = '<item id=\"file_%s\" href=\"%s\" media-type=\"application/xhtml+xml\"/>' % (\n",
    "        i + 1, basename) + manifest\n",
    "    spine = '<itemref idref=\"file_%s\" />' % (i + 1)\n",
    "    html_content = open(html,'r',encoding='utf-8').read()\n",
    "    print(html_content)\n",
    "    epub.writestr('OEBPS/' + basename, html_content)\n",
    "\n",
    "epub.writestr('OEBPS/Content.opf', index_tpl % {\n",
    "    'manifest': manifest,\n",
    "    'spine': spine,\n",
    "})"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
